import React from 'react'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import Screen from "../../../../components/Base/Screen";
import ContentWrap from "../../../../components/Base/ContentWrap";
import {SystemConfig} from "../../../../router/router";
import CommonUtil from "../../../../utils/CommonUtil";
import {Button, Card, Col, Form, Input, Row, Tree} from 'antd';
import Api from "../../../../configs/Api";

const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;

class BrandAdd extends Screen {
    constructor(props) {
        super(props);

        this.state = {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],

        }
    };

    componentDidMount() {
        if (this.props.pageData) {
            this.props.form.setFieldsValue({
                account: this.props.pageData.get('account', ''),
                nickname: this.props.pageData.get('nickname', ''),
                email: this.props.pageData.get('email', ''),
                remark: this.props.pageData.get('remark', ''),
            });

            this.setState({
                checkedKeys: JSON.parse(this.props.pageData.get('rights', '[]')),
            })
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                if (this.state.checkedKeys.length <= 0) return CommonUtil.toast('请选择菜单权限');

                values.rights = JSON.stringify(this.state.checkedKeys);

                if (this.props.pageData) values.id = this.props.pageData.get('id', '');

                let req = await this.request(Api.USER_SAVE, values);
                if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);
                CommonUtil.toast(req.msg);
                this.props.history.goBack();
            }
        });
    };

    onExpand = (expandedKeys) => {
        console.log('onExpand', expandedKeys);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = (checkedKeys) => {
        console.log('onCheck', checkedKeys);
        this.setState({checkedKeys});
    };

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({selectedKeys});
    };

    renderTreeNodes = (data) => {
        return data.map((item) => {
            // if(item.pass) return null;

            if (item.subMenu && item.subMenu.length > 0) {
                return (
                    <TreeNode title={item.name} key={item.path} dataRef={item}>
                        {this.renderTreeNodes(item.subMenu)}
                    </TreeNode>
                );
            }
            return <TreeNode title={item.name} key={item.path}/>;
        });
    };

    render() {
        const {getFieldDecorator} = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 20},
            },
        };

        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        };

        return (
            <ContentWrap>
                <Card title={'添加后台用户'} extra={<Button onClick={() => {
                    this.props.history.goBack()
                }}>返回</Button>} bordered={false} style={{marginTop: '20px'}}>
                    <Form
                        onSubmit={this.handleSubmit}
                    >
                        <FormItem
                            {...formItemLayout}
                            label="账号"
                        >
                            {getFieldDecorator('account', {
                                rules: [{required: true, message: '账号不能为空!'}],
                            })(
                                <Input type="text"/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="后台用户姓名"
                        >
                            {getFieldDecorator('nickname', {
                                rules: [{required: true, message: '后台用户姓名不能为空!'}],
                            })(
                                <Input type="text"/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="邮箱"
                        >
                            {getFieldDecorator('email', {
                                rules: [{required: true, message: '邮箱不能为空!'}],
                            })(
                                <Input type="email"/>
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="菜单权限"
                        >
                            {getFieldDecorator('rights', {})(
                                <Row style={{
                                    border: '1px solid #d9d9d9',
                                    height: '400px',
                                    overflowY: 'scroll',
                                    borderRadius: '4px'
                                }}>
                                    <Col>
                                        <Tree
                                            checkable
                                            showLine
                                            onExpand={this.onExpand}
                                            expandedKeys={this.state.expandedKeys}
                                            autoExpandParent={this.state.autoExpandParent}
                                            onCheck={this.onCheck}
                                            checkedKeys={this.state.checkedKeys}
                                            onSelect={this.onSelect}
                                            selectedKeys={this.state.selectedKeys}
                                        >
                                            {this.renderTreeNodes(SystemConfig.menu)}
                                        </Tree>
                                    </Col>
                                </Row>
                            )}
                        </FormItem>


                        <FormItem
                            {...formItemLayout}
                            label="备注信息"
                        >
                            {getFieldDecorator('remark', {})(
                                <Input.TextArea style={{height: "200"}}/>
                            )}
                        </FormItem>

                        <FormItem {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit">提交</Button>
                        </FormItem>
                    </Form>
                </Card>
            </ContentWrap>
        )
    }
}

export default withRouter(connect(
    state => ({
        pageData: state.root.app.get('pageData'),
    })
)(Form.create()(BrandAdd)))





